package com.qm.datax.beans;

import com.qm.datax.configuration.Configuration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.hutool.core.lang.Console.log;

/**
 * @Author：wangshali
 * @CreateTime：2024-12-16
 * @Description：
 * @Source:
 * @Sink:
 * @Version：v1.0
 */

public class Table {
    private final String tableName;
    private final List<Column> columns;

    public Table(String tableName) {
        this.tableName = tableName;
        this.columns = new ArrayList<>();

    }

    public String name() {
        return tableName;
    }

    public void addColumn(String name, String type) {
        columns.add(new Column(name, type));
    }

    public List<String> getColumnNames() {
        return columns.stream().map(Column::name).collect(Collectors.toList());
    }

    //stg增加审计列
    public List<Map<String, String>> getColumnNamesAndTypes() {
        List<Map<String, String>> result = new ArrayList<>();
        columns.forEach(column -> {
            Map<String, String> temp = new HashMap<>();
            temp.put("name", column.name());
            temp.put("type", column.hiveType());
            result.add(temp);

        });
        return result;
    }

    public List<Map<String, String>> getColumnAndIndex() {
        List<Map<String, String>> result = new ArrayList<>();
        int index=0;
        for (Column column : columns) {
            Map<String, String> temp = new HashMap<>();
            temp.put("index", index + "");
            temp.put("type", column.hiveType());
            result.add(temp);
            index++;
        }
        return result;
    }


    public  List<String> getQuerySql() {
        List<String> querySql = new ArrayList<>();

        //拼接sql
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT ");
        sql.append(String.join(",", columns.stream().map(Column::name).collect(Collectors.toList())));
        //加上stg审计列
        sql.append(",'" + Configuration.MYSQL_DATABASE + "'");
        sql.append(",'" + tableName + "'");
        sql.append(", now(), now(), now()");
        sql.append(" FROM ");
        sql.append(tableName);
        sql.append(" WHERE update_time BETWEEN  str_to_date( '$START_TIME', '%Y-%m-%d %H:%i:%s' ) AND str_to_date( '$END_TIME', '%Y-%m-%d %H:%i:%s' ) " +
                " OR create_time BETWEEN  str_to_date( '$START_TIME', '%Y-%m-%d %H:%i:%s' ) AND str_to_date( '$END_TIME', '%Y-%m-%d %H:%i:%s' )  ");

        log("sql: " + sql);

        querySql.add(sql.toString());

        return querySql;
    }

    public List<Map<String, String>> getColumnAndComment() {

        return null;
    }
}
